package utils

import (
	"encoding/json"
	"net/http"
	"reflect"
	"time"

	"golang.org/x/text/cases"
	"golang.org/x/text/language"
)

func Response(w http.ResponseWriter, code int, msg string, data ...any) {
	responseData := map[string]any{
		"code": code,
		"msg":  msg,
	}
	if len(data) > 0 {
		responseData["data"] = data[0]
	} else {
		responseData["data"] = nil
	}
	w.Header().Set("Content-Type", "application/json")
	if err := json.NewEncoder(w).Encode(responseData); err != nil {
		http.Error(w, "JSON编码失败", http.StatusInternalServerError)
	}
}

func GetCurrentTimestamp() int64 {
	return time.Now().Unix()
}
func TimestampToDateTime(timestamp int64) string {
	return time.Unix(timestamp, 0).Format("2006-01-02 15:04:05")
}

func GetFieldValue(obj any, key string) (any, bool) {
	v := reflect.ValueOf(obj)
	switch v.Kind() {
	case reflect.Map:
		val := v.MapIndex(reflect.ValueOf(key))
		return val.Interface(), val.IsValid()
	case reflect.Struct:
		caser := cases.Title(language.English) // 转换为首字母大写的字段名
		field := v.FieldByName(caser.String(key))

		if field.IsValid() && field.CanInterface() {
			return field.Interface(), true
		}
		return nil, false
	default:
		return nil, false
	}
}
